package com.javen.demo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ProductConsumer2 {
    private int number = 0;

    public synchronized void increment() {
        try {
            // 判断
            while (number != 0) {
                // 等待
                this.wait();
            }
            // 操作
            number++;
            log.info(" {} number: {} ", Thread.currentThread().getName(), number);
            // 通知唤醒
            this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void decrement() {
        try {
            // 判断
            while (number != 1) {
                // 等待
                this.wait();
            }
            // 操作
            number--;
            log.info(" {} number: {} ", Thread.currentThread().getName(), number);
            // 通知唤醒
            this.notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ProductConsumer2 prodConsumer = new ProductConsumer2();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                prodConsumer.increment();
            }
        }, "T1").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                prodConsumer.decrement();
            }
        }, "T2").start();
    }
}
